package com.jiyun.order.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.github.pagehelper.PageInfo;
import com.jiyun.order.mapper.FeeInfoMapper;
import com.jiyun.order.mapper.GoodsInfoMapper;
import com.jiyun.order.service.IOrdersService;
import com.jiyun.orders.pojo.GoodsInfo;
import com.jiyun.orders.pojo.Orders;
import com.jiyun.orders.pojo.OrdersExcel;
import com.jiyun.orders.vo.OrderWrapper;
import com.jiyun.orders.vo.OrdersVo;
import com.jiyun.orders.vo.ResultVo;
import com.jiyun.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单基础信息表 前端控制器
 * </p>
 *
 * @author 1823.
 * @since 2025-02-12
 */
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private IOrdersService ordersService;


    @Operation(summary = "查询订单")
    @RequestMapping("/getOrders")
    public ResultVo getOrders(Integer pageNum,Integer pageSize, @RequestBody OrdersVo ordersVo){
        PageInfo<Orders> pageInfo=ordersService.getOrders(pageNum,pageSize,ordersVo);
        return ResultVo.ok(pageInfo);
    }

    @Operation(summary = "添加订单")
    @RequestMapping("/addOrders")
    public Result<String> addOrders(@RequestBody OrderWrapper orderWrapper) {
        ordersService.addOrders(orderWrapper);
        return Result.ok();
    }

    @Operation(summary = "订单详情")
    @RequestMapping("/getOrdersDetail/{id}")
    public ResultVo getOrdersDetail(@PathVariable Integer id){
        Orders orders=ordersService.getOrdersDetail(id);
        return ResultVo.ok(orders);
    }

    @Operation(summary = "导出订单")
    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Orders> list= ordersService.findAll();

        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFSheet sheet = workBook.createSheet();

        XSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("订单号");
        titleRow.createCell(1).setCellValue("客户名称");
        titleRow.createCell(2).setCellValue("客户编码");
        titleRow.createCell(3).setCellValue("始发地");
        titleRow.createCell(4).setCellValue("目的地");
        titleRow.createCell(5).setCellValue("订单状态");
        titleRow.createCell(6).setCellValue("收货人");
        titleRow.createCell(7).setCellValue("发货人");
        titleRow.createCell(8).setCellValue("合同");
        titleRow.createCell(9).setCellValue("运输类型");
        titleRow.createCell(10).setCellValue("货物类型");
        titleRow.createCell(11).setCellValue("订单来源");
        titleRow.createCell(12).setCellValue("订单备注");
        titleRow.createCell(13).setCellValue("下单时间");
        titleRow.createCell(14).setCellValue("货物数量");
        titleRow.createCell(15).setCellValue("货物体积");
        titleRow.createCell(16).setCellValue("货物重量");
        titleRow.createCell(17).setCellValue("运费合计");
        titleRow.createCell(18).setCellValue("创建人");
        // 创建 DecimalFormat 用于格式化 BigDecimal
        DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
        for(int i=0;i<list.size();i++){
            Orders s=list.get(i);
            XSSFRow row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(s.getOrderId());
            row.createCell(1).setCellValue(s.getCustomerName());
            row.createCell(2).setCellValue(s.getCustomerCode());
            row.createCell(3).setCellValue(s.getOrigin());
            row.createCell(4).setCellValue(s.getDestination());
            row.createCell(5).setCellValue(s.getOrderStatus()==1?"待审核":
                   s.getOrderStatus()==2?"待调度":
                   s.getOrderStatus()==3?"运输中":
                   s.getOrderStatus()==4?"已签收":
                   s.getOrderStatus()==5?"已拒绝":"已取消");
            row.createCell(6).setCellValue(s.getConsignee());
            row.createCell(7).setCellValue(s.getShipper());
            row.createCell(8).setCellValue(s.getContract());
            row.createCell(9).setCellValue(s.getTransportationType());
            row.createCell(10).setCellValue(s.getGoodsType());
            row.createCell(11).setCellValue(s.getOrderSource());
            row.createCell(12).setCellValue(s.getRemarks());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(s.getOrderTime());
            row.createCell(13).setCellValue(format);
            // 检查货物数量是否为 null
            if (s.getQuantity() != null) {
                row.createCell(14).setCellValue(s.getQuantity());
            } else {
                row.createCell(14).setCellValue("");
            }
            // 处理货物体积
            if (s.getVolume() != null) {
                row.createCell(15).setCellValue(decimalFormat.format(s.getVolume()));
            } else {
                row.createCell(15).setCellValue("");
            }
            // 处理货物重量
            if (s.getWeight() != null) {
                row.createCell(16).setCellValue(decimalFormat.format(s.getWeight()));
            } else {
                row.createCell(16).setCellValue("");
            }
            // 处理运费合计
            if (s.getTotalFee() != null) {
                row.createCell(17).setCellValue(decimalFormat.format(s.getTotalFee()));
            } else {
                row.createCell(17).setCellValue("");
            }
            row.createCell(18).setCellValue(s.getName());
        }
        response.setHeader("content-disposition", "attachment;filename=orders.xlsx");
        workBook.write(response.getOutputStream());
        workBook.close();
    }

    @Autowired
    private GoodsInfoMapper goodsInfoMapper;



    //订单导入
    @Operation(summary = "订单导入")
    @RequestMapping("importExcel")
    public void importExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), OrdersExcel.class, new ReadListener<OrdersExcel>() {
            // 每读取一行数据，这个方法就会被自动调用
            @Override
            public void invoke(OrdersExcel ordersExcel, AnalysisContext analysisContext) {
                try {
                    Orders orders = new Orders();
                    BeanUtils.copyProperties(ordersExcel, orders);
                    orders.setOrderStatus(ordersExcel.getOrderStatus().equals("待审核") ? 1 :
                            ordersExcel.getOrderStatus().equals("待调度") ? 2 :
                            ordersExcel.getOrderStatus().equals("运输中") ? 3 :
                            ordersExcel.getOrderStatus().equals("已签收") ? 4 :
                            ordersExcel.getOrderStatus().equals("已拒绝") ? 5 :6);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date time = simpleDateFormat.parse(ordersExcel.getOrderTime());
                    orders.setOrderTime(time);

//                    GoodsInfo goodsInfo = goodsInfoMapper.findByQuantity(ordersExcel.getQuantity());
//                    orders.setGid(goodsInfo.getId());
//                    Supplier supplier = supplierFeign.findBySname(shoppExcel.getSname());
//                    shopp.setSid(supplier.getId());
//                    shopp.setId(null);
                    ordersService.addOrder(orders);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            // 如果所有的数据都读取完了，则调用这个方法
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.println("--------数据读取完毕！！！--------");
            }
        }).sheet(0).doRead();
    }
}
